package com.nantes.nantourage.app;

import java.io.IOException;

import android.app.Application;
import android.database.SQLException;
import android.util.Log;

import com.nantes.nantourage.dao.DataBaseHelper;
import com.nantes.nantourage.dao.PreferencesHelper;

/**
 * Singleton repr�sentant l'application ASCT
 */
public class SPApplication extends Application {

    /**
     * L'instance de l'application
     */
    private static SPApplication instance;

    /**
     * Indique si la m�thode onCreate est termin�e
     */
    private boolean isCreated = false;

    /**
     * Le gestionnaire des pr�f�rences (SharedPreferences)
     */
    private PreferencesHelper preferences;

    /**
     * Le gestionnaire de base de donn�es
     */
    private DataBaseHelper database;

    /**
     * Retourne l'instance singleton de l'application
     * 
     * @return
     */
    public static SPApplication getInstance() {
        return instance;
    }

    /**
     * Indique si la m�thode onCreated a �t� appel�e et est termin�e
     * 
     * @return
     */
    public boolean isCreated() {
        return isCreated;
    }

    /**
     * Retourne l'instance d'acc�s aux pr�f�rences locales
     * 
     * @return
     */
    public PreferencesHelper getPreferences() {
        return preferences;
    }

    /**
     * Retourne l'instance d'acc�s � la base de donn�es
     * 
     * @return
     */
    public DataBaseHelper getDataBase() {
        return database;
    }

    @Override
    public void onCreate() {

        instance = this;

        this.initDataBase();

        super.onCreate();

        this.isCreated = true;
    }

    /**
     * Initialise la base de donn�es
     */
    private void initDataBase() {
        database = new DataBaseHelper(getApplicationContext());
        try {
            database.createDataBase();
        } catch (IOException ioe) {
            Log.e("Unable to create database", ioe.toString());
        }
        try {
            database.openDataBase();
        } catch (SQLException sqle) {
            Log.e("Unable to open database", sqle.toString());
            throw sqle;
        }
    }
}
